// wallet.js
Page({
  data: {
    balance: 0,
    points: 0,
    transactions: [],
    loading: false
  },

  onLoad() {
    this.loadWalletData()
  },

  onShow() {
    this.loadWalletData()
  },

  // 加载钱包数据
  loadWalletData() {
    this.setData({ loading: true })
    
    // 从API获取钱包数据
    this.getWalletDataFromAPI()
  },

  // 从API获取钱包数据
  getWalletDataFromAPI() {
    wx.request({
      url: 'http://localhost:8082/user/wallet',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        this.setData({ loading: false })
        
        if (res.data && res.data.code === 200) {
          this.setData({
            balance: res.data.data.balance || 0,
            points: res.data.data.points || 0,
            transactions: res.data.data.transactions || []
          })
        } else {
          this.setData({
            balance: 0,
            points: 0,
            transactions: []
          })
        }
      },
      fail: (err) => {
        console.error('获取钱包数据失败:', err)
        this.setData({ 
          loading: false,
          balance: 0,
          points: 0,
          transactions: []
        })
      }
    })
  },

  // 充值
  onRecharge() {
    wx.showActionSheet({
      itemList: ['充值10元', '充值50元', '充值100元', '自定义金额'],
      success: (res) => {
        const amounts = [10, 50, 100, 0]
        const amount = amounts[res.tapIndex]
        
        if (amount === 0) {
          // 自定义金额
          wx.showModal({
            title: '自定义充值',
            editable: true,
            placeholderText: '请输入充值金额',
            success: (modalRes) => {
              if (modalRes.confirm && modalRes.content) {
                this.processRecharge(parseFloat(modalRes.content))
              }
            }
          })
        } else {
          this.processRecharge(amount)
        }
      }
    })
  },

  // 处理充值
  processRecharge(amount) {
    if (amount <= 0) {
      wx.showToast({
        title: '充值金额必须大于0',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '确认充值',
      content: `确定要充值${amount}元吗？`,
      success: (res) => {
        if (res.confirm) {
          // 充值成功
          const newBalance = this.data.balance + amount
          const newTransaction = {
            id: Date.now(),
            type: 'recharge',
            amount: amount,
            description: '账户充值',
            time: new Date().toLocaleString(),
            status: 'success'
          }
          
          this.setData({
            balance: newBalance,
            transactions: [newTransaction, ...this.data.transactions]
          })
          
          wx.showToast({
            title: '充值成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 提现
  onWithdraw() {
    wx.showModal({
      title: '提现',
      content: '提现功能暂未开放，敬请期待',
      showCancel: false
    })
  },

  // 查看交易记录
  onViewTransactions() {
    wx.navigateTo({
      url: '/pages/transactions/transactions'
    })
  },

  // 积分兑换
  onPointsExchange() {
    wx.showActionSheet({
      itemList: ['10积分=1元', '100积分=10元', '1000积分=100元'],
      success: (res) => {
        const rates = [
          { points: 10, amount: 1 },
          { points: 100, amount: 10 },
          { points: 1000, amount: 100 }
        ]
        
        const rate = rates[res.tapIndex]
        if (this.data.points >= rate.points) {
          wx.showModal({
            title: '确认兑换',
            content: `确定要用${rate.points}积分兑换${rate.amount}元吗？`,
            success: (modalRes) => {
              if (modalRes.confirm) {
                this.setData({
                  points: this.data.points - rate.points,
                  balance: this.data.balance + rate.amount
                })
                
                wx.showToast({
                  title: '兑换成功',
                  icon: 'success'
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '积分不足',
            icon: 'none'
          })
        }
      }
    })
  },

  // 设置支付密码
  onSetPassword() {
    wx.showModal({
      title: '设置支付密码',
      content: '支付密码功能暂未开放，敬请期待',
      showCancel: false
    })
  },

  // 绑定银行卡
  onBindCard() {
    wx.showModal({
      title: '绑定银行卡',
      content: '银行卡绑定功能暂未开放，敬请期待',
      showCancel: false
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadWalletData()
    wx.stopPullDownRefresh()
  }
})
